package com.hncic.tx.center.mvc.util;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hncic.tx.center.common.exception.ApiException;
import com.hncic.tx.center.common.util.Constant;
import com.hncic.tx.center.common.vo.JsonData0;

/**
 * @author smj E-mail: 463136320@qq.com
 * @created 2017年8月18日 下午2:23:15
 * @since jdk1.8 
 * @version 1.0
 * @describe 
 */
@ControllerAdvice
public class HttpExceptionHandler {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public JsonData0 defaultErrorHandler(HttpServletRequest req, Exception ex) throws Exception {
		JsonData0 res = new JsonData0();
		res.setMsg(ex.getMessage());
		if (ex instanceof org.springframework.web.servlet.NoHandlerFoundException) {
			res.setCode(404);
		} else {
			res.setCode(500);
			if (ex instanceof ServletRequestBindingException
					&& StringUtils.contains(ex.getMessage(), Constant.TxSessKey)) {
				res.setMsg("当前用户未登录，请重新登录系统!!!!!");
			} else if (ex instanceof ApiException) {
				res.setCode(((ApiException) ex).getCode());
			}

		}
		logger.warn("GlobalExceptionHandler.defaultErrorHandler path:{},error:", req.getContextPath(), res);
		return res;
	}
}
